//
//  ChannelsDetailViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/9/10.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "ChannelsDetailViewController.h"
#import "TAMacro.h"
#import "UIView+Frame.h"
#import "AFNetworking.h"
#import "ChannelContent.h"
#import "ChannelCellFrameViewModel.h"
#import "ChannelCell.h"
#import "ChannelRankListTableViewCell.h"
#import "ChannelPostModel.h"
#import "UIButton+WebCache.h"
#import "ChannelPostStar.h"
#import "ChannelPostModel.h"
#import "ChannelPostToolbar.h"
#import "ChannelPostContent.h"
#import "ChannelPostHotposts.h"
#import "ChannelPostJoin.h"
#import "ChanelDeTailToolBar.h"
#import "ChannelPresentationCellFrameViewModel.h"
#import "UIImageView+WebCache.h"

#import "ChannelPostModel.h"
#import "ChannelHotPostsTableViewCell.h"
#import "PersonalViewController.h"
#import "ChannelContent.h"
#import "ChannelRankListViewController.h"
#import "PostsDetailViewController.h"
#import "ChannelToolBarButton.h"
#import "ChannelPosts.h"
#import "PostVoiceViewController.h"

@interface ChannelsDetailViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    clickActionDelegate
>

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UITableView *channelsDetailTableView;
@property (nonatomic, strong) ChanelDeTailToolBar *toolView;

@property (nonatomic, assign) CGFloat lastContentOffset_Y;
@property (nonatomic, assign) BOOL willDecelerating;

@property (nonatomic, strong) NSMutableArray *channelSArray;

@property (nonatomic, strong) ChannelPresentationCellFrameViewModel *channelPresentationCellFrameViewModel;

@property (nonatomic, strong) UIImageView *headImage;
@property (nonatomic, strong) UILabel *headLabel;
@property (nonatomic, strong) UIView *headerView;


@end

@implementation ChannelsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createTableView];
    [self createTableHeaderView];
    [self createToolView];
    [self netWork];
    [self firstNetWork];
    [self createNavigationBar];
}

- (void)setChannelID:(NSString *)channelID {
    _channelID = channelID;
    [self netWork];
    [self firstNetWork];
}


- (void)createTableView {
    
    self.channelsDetailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    
    [self.view addSubview:_channelsDetailTableView];
    _channelsDetailTableView.dataSource = self;
    _channelsDetailTableView.delegate = self;
    [_channelsDetailTableView registerClass:[ChannelCell class] forCellReuseIdentifier:@"reuse"];
    
    [_channelsDetailTableView registerClass:[ChannelRankListTableViewCell class] forCellReuseIdentifier:@"ChannelRankListTableViewCellReuse"];
    [_channelsDetailTableView registerClass:[ChannelHotPostsTableViewCell class] forCellReuseIdentifier:@"ChannelHotPostsTableViewCellReuse"];

// tableView取消回弹效果
    _channelsDetailTableView.bounces = NO;
    _channelsDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}

- (void)createTableHeaderView {
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    _headerView.backgroundColor = [UIColor colorWithRed:55 / 255.0 green:55 / 255.0 blue:55 / 255.0 alpha:1];
    self.headImage = [[UIImageView alloc] initWithFrame:CGRectMake(4 * ViewMargin, ViewMargin, 60, 60)];
    _headImage.contentMode = UIViewContentModeScaleAspectFill;
    _headImage.layer.masksToBounds = YES;
//    _headImage.backgroundColor = [UIColor yellowColor];
    [_headerView addSubview:_headImage];
    
    self.headLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headImage.frame) + ViewMargin * 2, ViewMargin, SCREEN_WIDTH - CGRectGetWidth(_headImage.frame) - 10 * ViewMargin, 60)];
//    _headLabel.backgroundColor = [UIColor greenColor];
    _headLabel.textColor = [UIColor whiteColor];
    _headLabel.numberOfLines = 0;
    _headLabel.font = TextFont;
    [_headerView addSubview:_headLabel];
    _channelsDetailTableView.tableHeaderView = _headerView;

}

- (void)firstNetWork {
    
//    c=Search&m=getChannelInfo&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22channelId%22%3A%225715d44c43bef4e12cea5e28%22%7D&t=t&v=v105
//    {"uid":"57c01d33a9a36d0621c123f7","channelId":"5715d44c43bef4e12cea5e28"}
    NSString *userid = @"57c01d33a9a36d0621c123f7";
    NSString *text = [NSString stringWithFormat:@"{\"uid\":\"%@\",\"channelId\":\"%@\"}", userid, _channelID];
    //    NSLog(@"%@", text);
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSString *parmeters = [NSString stringWithFormat:@"c=Post&m=postDetail&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%225723ebe4a9a36d3340a304b6%22%7D&t=t&v=v105", utf8Text];
    
    NSString *parmeters = [NSString stringWithFormat:@"c=Search&m=getChannelInfo&p=%@&t=t&v=v105", utf8Text];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ChannelPostModel *channelPost = [ChannelPostModel modelWithDic:responseObject];
        // 转化成 viewModel
        self.channelPresentationCellFrameViewModel = [[ChannelPresentationCellFrameViewModel alloc] init];
        _channelPresentationCellFrameViewModel.channelPost = channelPost;
        [_channelsDetailTableView reloadData];

        
        
        // 头视图上的图片
        [_headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://qn.zheli.io/%@", _channelPresentationCellFrameViewModel.channelPost.content.img]]];
        // 透视图上的说明文字
        _headLabel.text = _channelPresentationCellFrameViewModel.channelPost.content.desc;
        // 工具栏的赋值
        _toolView.toolBar = _channelPresentationCellFrameViewModel.channelPost.content.toolbar;
        self.titleLabel.text = _channelPresentationCellFrameViewModel.channelPost.content.content;


    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];

    
    
    
    
}
// 网络请求
- (void)netWork {
    // c=Search&m=getChannelPost&p=%7B%22channelId%22%3A%225715d44c43bef4e12cea5e28%22%2C%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105
    //      %7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%2257cedc1ba9a36d926cc123d8%22%7D
//     {"channelId":"5715d44c43bef4e12cea5e28","uid":"57c01d33a9a36d0621c123f7"}
    
    NSString *userid = @"57c01d33a9a36d0621c123f7";
    NSString *text = [NSString stringWithFormat:@"{\"channelId\":\"%@\",\"uid\":\"%@\"}", _channelID, userid];
    //    NSLog(@"%@", text);
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    //    NSLog(@"%@", utf8Text);
    //    NSString *p = [self URLEncodedString:utf8Text];
    //    NSString *parmeters = [NSString stringWithFormat:@"c=Post&m=postDetail&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%2C%22pid%22%3A%225723ebe4a9a36d3340a304b6%22%7D&t=t&v=v105", utf8Text];
    
    NSString *parmeters = [NSString stringWithFormat:@"c=Search&m=getChannelPost&p=%@&t=t&v=v105", utf8Text];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
        NSArray *array = responseObject[@"content"];
        self.channelSArray = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            ChannelContent *channelContent = [ChannelContent modelWithDic:dic];
            ChannelCellFrameViewModel *viewModel = [[ChannelCellFrameViewModel alloc] init];
            viewModel.channelContent = channelContent;
            [_channelSArray addObject:viewModel];
        }
        [_channelsDetailTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChannelCellFrameViewModel *viewModel = _channelSArray[indexPath.row];
    if (_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts.count == 0 || _channelPresentationCellFrameViewModel.channelPost.content.rankList.count == 0) {
        return viewModel.cellHeight;
    } else {
        
        if (indexPath.section == 0) {
            
            return _channelPresentationCellFrameViewModel.rankListCellHeight;
        } else if (indexPath.section == 1) {
            return _channelPresentationCellFrameViewModel.hotPostCellHeight;
        }
        
        return viewModel.cellHeight;
        
    }
    
}

// 应该分三个区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts.count == 0 || _channelPresentationCellFrameViewModel.channelPost.content.rankList.count == 0) {
        return 1;
    }
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts.count == 0 || _channelPresentationCellFrameViewModel.channelPost.content.rankList.count == 0) {
        return _channelSArray.count;
    } else {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            return 1;
        }
        return _channelSArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts.count == 0 || _channelPresentationCellFrameViewModel.channelPost.content.rankList.count == 0) {
            ChannelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
            cell.channelCellFrame = _channelSArray[indexPath.row];
            return cell;
    } else {
        
        if (indexPath.section == 0) {
            ChannelRankListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChannelRankListTableViewCellReuse"];
            cell.channelPresentationCellFrameViewModel = _channelPresentationCellFrameViewModel;
            return cell;
        } else if (indexPath.section == 1) {
            ChannelHotPostsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChannelHotPostsTableViewCellReuse"];
            
            cell.channelPresentationCellFrameViewModel = _channelPresentationCellFrameViewModel;
            NSLog(@"%@", _channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts[indexPath.row].postType);
           // 如果postType的样式为Voice那么POST到音乐播放界面
            if ( [_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts[indexPath.row].postType isEqualToString:@"Voice"]) {
                __weak typeof(self) weakSelf = self;
                PostVoiceViewController *voiceVC = [[PostVoiceViewController alloc] init];
                cell.postDetailPage = ^(NSString *str){
                    [weakSelf.navigationController pushViewController:voiceVC animated:YES];
                    voiceVC.postId = str;
                };
                return cell;
            }
            
            // 如果postType的样式为Image那么POST到图片播放界面
            __weak typeof(self) weakSelf = self;
            PostsDetailViewController *postDetailVC = [[PostsDetailViewController alloc] init];
            cell.postDetailPage = ^(NSString *str){
                [weakSelf.navigationController pushViewController:postDetailVC animated:YES];
                postDetailVC.postId = str;
            };

            return cell;
        }
        ChannelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        ChannelCellFrameViewModel *viewModel = _channelSArray[indexPath.row];
        cell.channelCellFrame = viewModel;
        // 页面跳转
        __weak typeof(self) weakSelf = self;
        PersonalViewController *personalVC = [[PersonalViewController alloc] init];
        cell.channelContentView.clickAction = ^(){
            NSLog(@"block点击跳转");
            [weakSelf.navigationController pushViewController:personalVC animated:YES];
            personalVC.postId = viewModel.channelContent.uid;
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts.count == 0 || _channelPresentationCellFrameViewModel.channelPost.content.rankList.count == 0) {
        NSLog(@"帖子");
    } else {
        
        if (indexPath.section == 0) {
            NSLog(@"精选排行榜");
            ChannelRankListViewController *rankListVC = [[ChannelRankListViewController alloc] init];
            rankListVC.rankList = _channelPresentationCellFrameViewModel.channelPost.content.rankList;
            [self.navigationController pushViewController:rankListVC animated:YES];
        } else if (indexPath.section == 1) {
            NSLog(@"精选");
        } else {
            NSLog(@"帖子");
            if ( [_channelPresentationCellFrameViewModel.channelPost.content.hotPosts.posts[indexPath.row].postType isEqualToString:@"Voice"]) {

                PostVoiceViewController *voiceVC = [[PostVoiceViewController alloc] init];
                [self.navigationController pushViewController:voiceVC animated:YES];
                ChannelCellFrameViewModel *viewModel = _channelSArray[indexPath.row];

                voiceVC.postId = viewModel.channelContent.ID;
               
                
            } else {
                
                // 如果postType的样式为Image那么POST到图片播放界面

                PostsDetailViewController *postDetailVC = [[PostsDetailViewController alloc] init];
                [self.navigationController pushViewController:postDetailVC animated:YES];
                ChannelCellFrameViewModel *viewModel = _channelSArray[indexPath.row];
                
                postDetailVC.postId = viewModel.channelContent.ID;
                
            }
            

            
            
            
        }
    }
}

// 页面下方的工具条
- (void)createToolView {
//    ChanelDeTailToolBar *toolBar = [[ChanelDeTailToolBar alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
//    toolBar.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:toolBar];
//    toolBar.toolBarButton.delegate = self;
//
//
//    _toolView = toolBar;
    
    
    self.toolView = [[ChanelDeTailToolBar alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
    _toolView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_toolView];
    _toolView.toolBarButton.delegate = self;
    
}

- (void)clickAction {
    NSLog(@"草泥马");
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.lastContentOffset_Y = scrollView.contentOffset.y;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y - _lastContentOffset_Y > 0) {
//        NSLog(@"向上");
        [UIView animateWithDuration:0.3 animations:^{
            _toolView.ltq_y = SCREEN_HEIGHT;
        }];
    } else {
//        NSLog(@"向下");
        [UIView animateWithDuration:0.3 animations:^{
            _toolView.ltq_y = SCREEN_HEIGHT - 44;
        }];
    }
}


- (void)createNavigationBar {
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 27, 30, 30)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backView addSubview:backButton];
    [backButton addTarget:self action:@selector(popViewControllerAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 40, 27, 30, 30)];
    [moreButton setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [self.backView addSubview:moreButton];
    [moreButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    

    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    _titleLabel.center = CGPointMake(SCREEN_WIDTH / 2, 42);
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = 1;
    [self.backView addSubview:_titleLabel];

}

- (void)moreAction:(UIBarButtonItem *)barButtonItem {
    NSLog(@"更多");
}

- (void)popViewControllerAction: (UIBarButtonItem *)barButtonItem {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
